package com.zj.thread.callable;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.concurrent.*;

public class CallableTest {
    static boolean[] taskflag={false};

    public static void main(String[] args) {
      ExecutorService executor = new ThreadPoolExecutor(0, 4,
              0L, TimeUnit.MILLISECONDS,
              new LinkedBlockingQueue<Runnable>());
      //创建一个Callable，3秒后返回String类型
      System.out.println("提交任务之前 "+getStringDate());
      int taskNums=10;
      List<Future> futures= new ArrayList<Future>();
      for(int i=0;i<taskNums;i++){
          taskflag[0]=true;
          futures.add(executor.submit(new MyTask(i)));
      }
        executor.submit(new CountTask(futures,taskflag));

        System.out.println("提交任务之后，获取结果之前 "+getStringDate());
        executor.shutdown();
    }
    public static String getStringDate() {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
        String dateString = formatter.format(currentTime);
        return dateString;
    }
    static class CountTask implements Callable<Integer> {
        List<Future> futures;
        boolean taskflag[];

        CountTask(List<Future> futures,boolean taskflag[]){
            this.futures=futures;
            this.taskflag=taskflag;
        }
        @Override
        public Integer call() throws Exception {
            System.out.println("任务结束:"+CallableTest.getStringDate());
            int count=0;
            for(int i=0;i<futures.size();i++){
                try {

                    int res= (int) futures.get(i).get();
                    System.out.println("futures["+i+"],res:"+res);
                    count ++;
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            System.out.println(taskflag[0]);
            taskflag[0]=false;
            System.out.println("count:"+count);
            System.out.println("最后时间:"+CallableTest.getStringDate());
            System.out.println(taskflag[0]);
            return 1;
        }
    }

}
